<template>
  <div class="app-container">
    <!-- 条件过滤区 -->
    <div class="filter-container">
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">关口名称：</span>
          <el-input size="small" placeholder="关口名称"
                    class=" date-range-item" v-model="searchObj.passName"/>
        </div>
         <div class="filter-item">
          <span class="filter-title">时间区间：</span>
          <el-date-picker
            size="small"
            class="search-item date-range-item"
            v-model="searchObj.timeRange"
            type="datetimerange"
            format="yyyy-MM-dd  HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :range-separator="null"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <!-- <div class="filter-item">
          <span class="filter-title">关口类型：</span>
          <el-select size="small" v-model="searchObj.isReportRiskEntry" class="search-item" placeholder="请选择">
            <el-option
              v-for="item in passTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div> -->
        <!-- <div class="filter-item">
          <span class="filter-title">人员属性：</span>
          <el-select size="small" v-model="searchObj.personTypeCode" class="search-item" placeholder="请选择">
            <el-option
              v-for="item in peopleTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div> -->
      </div>
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">出发地：</span>
          <el-cascader
            class="date-range-item"
            size="small"
            :props="beforeCityProps"
            v-model="searchObj.beforeCityIds"
          ></el-cascader>
        </div>
        <div class="filter-item">
          <span class="filter-title">目的地：</span>
          <el-cascader
            class="date-range-item"
            size="small"
            :props="residentialCityProps"
            v-model="searchObj.residentialCityIds"
          ></el-cascader>
        </div>
        <div class="filter-item" style="margin-left:1rem;">
          <el-button size="small" @click="search" class="" type="primary">
            查询
          </el-button>
          <el-button size="small" @click="reset" class="">
            重置
          </el-button>
          <el-button size="small" :loading="exportLoading" @click="exportExcel" class="filter-item" plain type="primary">
            导出
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      size="medium"
      :data="tabItems"
      ref="table"
      style="width: 100%;"
      v-loading="tabLoading"
    >
      <!-- <el-table-column label="序号" align="center"
        type="index"
      /> -->
      <el-table-column label="出发地" align="center"
      >
        <el-table-column label="省/市" align="center"
          prop="beforeProvince"
        /> 
        <el-table-column label="市/州" align="center"
          prop="beforeCity"
        /> 
        <el-table-column label="县/区" align="center"
          prop="beforeDistrict"
        /> 
      </el-table-column>
      <el-table-column label="入黔目的地" align="center"
      >
        <el-table-column label="省/市" align="center"
          prop="residentialProvince"
        /> 
        <el-table-column label="市/州" align="center"
          prop="residentialCity"
        /> 
        <el-table-column label="县/区" align="center"
          prop="residentialDistrict"
        /> 
      </el-table-column>
      <el-table-column label="入黔日期" align="center" prop="time">
        
      </el-table-column>
      <el-table-column label="关口类型" align="center"
        prop="passType"
      />
      <el-table-column label="关口名称" align="center"
        prop="passName"
      />
      <el-table-column label="关口所属区县" align="center"
        prop="passPertain"
      />
      <el-table-column label="关口反黔人数" align="center"
        prop="passPersonCount"
      />
      <el-table-column label="人员属性" align="center"
        prop="personType"
      />
      
    </el-table>
    <div class="pagination-box">
      <el-pagination
        :background="true"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-count="pagination.pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import areaConvert from '@/utils/areaCodeCov.js';
import {selectBackStatPage , commAreaUrl, commUserAreaUrl, exportBackStat} from '@/http/apiUrls.js';
import { getDateBefore } from '@/utils/date.js';
import { passType, peopleType } from '@/data/viaGzType.js';
export default {
  name: 'ViaGzReport',
  data() {
    return {
      tabLoading: false,
      exportLoading: false,
      tableKey: 0,
      pageItems: 10, // 每页查询条数
      pagination: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示条数
        pageCount: 1, // 总页数
      },
      passTypes: passType,
      peopleTypes: peopleType,
      tabItems: [],
      searchObj: this.initSearchObj(),
      beforeCityProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          const nodes = [];          
          let type = level == 0 ? '000000' : node.value;
          this.provinceFn(type)
            .then((res) => {
              // 节点数组
              res.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.fullName,
                  leaf: item.level >= 4
                };
                nodes.push(obj);
              });
              resolve(nodes);
            }).catch((error) => {
              console.log(error);
            });
        }
      },
      residentialCityProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          const nodes = [];          
          let type = level == 0 ? null : node.value;
          this.provinceFn(type)
            .then((res) => {
              // 节点数组
              res.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.fullName,
                  leaf: item.level >= 4
                };
                nodes.push(obj);
              });
              resolve(nodes);
            }).catch((error) => {
              console.log(error);
            });
        }
      },
    }
  },
  created(){
    let date = getDateBefore(1)
    this.getData(1, this.pageItems, {
      beginTime: date + ' 00:00:00',
      endTime: date + ' 23:59:59'
    }, {})
  },
  methods: {
    initSearchObj(){
      let date = getDateBefore(1)
      return {
        passName: '',
        timeRange: [
          date + ' 00:00:00',
          date + ' 23:59:59'
        ],
        beforeCityIds: [],
        residentialCityIds: []
      }
    },
    getSearchObj(){
      let obj = {...this.searchObj};
      // 时间
      if(obj.timeRange && obj.timeRange.length == 2 ){
        obj.beginTime = obj.timeRange[0]
        obj.endTime = obj.timeRange[1]
      }
      // 出发地
      const ids = obj.beforeCityIds;
      if(ids && ids.length > 0){
        let areaCode = ids[ids.length-1]
        let likeVal = areaConvert(areaCode);
        obj.beforeProvinceCode = likeVal
      }
      // 目的地
      const resIds = obj.residentialCityIds;
      if(resIds && resIds.length > 0){
        let areaCode = resIds[resIds.length-1]
        let likeVal = areaConvert(areaCode);
        obj.residentialProvinceCode = likeVal
      }
      return obj;
    },
    getExtraObj(){
      let extra = {};
      return extra
    },
    getArea(code){
      return new Promise((resolve, reject) => {
        const requestData = {
          parentCode: code
        }
        if(code){
          this.$postJson(commAreaUrl, requestData).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }else{
          this.$postJson(commUserAreaUrl, {}).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }
      })
    },
    // 获取省市区街道
    provinceFn(code) {
      // 此处是一个promise 直接返回
      return this.getArea(code);
    },
    // 监听数据变化
    handleChange(value) {
      console.log(value);
    },
    search(){
      this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    reset(){
      this.searchObj = this.initSearchObj()
      this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    getData(current , size, model, extra){
      let requestData = {
        current,
        size,
        model,
        extra
      }
      this.tabLoading = true;
      this.$postJson(selectBackStatPage, requestData).then(res => {
        this.tabLoading = false;
        if(res){
          const pagination = {
            currentPage: parseInt(res.current), // 当前页面号
            pageSize: parseInt(res.size), // 每页条目数
            pageCount: parseInt(res.pages), // 总页面数
          }
          this.pagination = pagination;
          this.tabItems = res.records;
        }
      })
    },
    async handleSizeChange(val) {
      this.pageItems = val
      await this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    async handleCurrentChange(val) {
      await this.getData(val, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    itemDetail(item){
      console.log(item);
      // this.$router.push({
      //   path: "/eve/bus-user/detail",
      //   query: {id: item.id}
      // })
    },
    exportExcel() {
      let requestData = {
        model: this.getSearchObj()
      }
      this.exportLoading = true
      this.$exportJson(exportBackStat, requestData).then(res => {
        this.exportLoading = false
        if(res){
          console.log(res);
          var b = new Blob([res], { type: "application/vnd.ms-excel" });
          // 根据传入的参数b创建一个指向该参数对象的URL
          var url = URL.createObjectURL(b);
          var link = document.createElement("a");
          // 导出的文件名
        
          let fileName = "旅居省返黔统计.xlsx";
          link.download = fileName;
          link.href = url;
          link.click();
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .filter-row {
    width: 100%;
    margin-bottom: 8px;
    display: flex;
    .filter-item {
      width: fit-content;
      .filter-title {
        display:inline-block;
        width:100px;
        text-align:right;
        margin-left: 4px;
      }
    }
  }
}
</style>